package com.smforj.ssm.modules.wc.controller;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.smforj.ssm.frame.core.utils.StringEx;
import com.smforj.ssm.frame.core.web.controller.BaseControllerSupportImpl;
import com.smforj.ssm.frame.core.web.domain.DataResult;
import com.smforj.ssm.modules.lib.domain.SysReader;
import com.smforj.ssm.modules.lib.domain.vo.SysBookVo;
import com.smforj.ssm.modules.lib.service.LibraryService;
import com.smforj.ssm.modules.sys.service.SysReaderService;
import com.smforj.ssm.modules.wc.constant.DevApp;
import com.smforj.ssm.modules.wc.domain.LoginInfo;
import com.smforj.ssm.modules.wc.service.BusinessService;
import com.smforj.ssm.modules.wc.util.HttpUtil;
import com.smforj.ssm.modules.wc.util.WechatConst;

import net.sf.json.JSONObject;

/***
 * 公共操作Controller
 * 针对微信小程序提供 ,该接口仅仅与图书管理软件进行通讯,采用的是条码模式
 * 
 * @author Haijun Gao 
 * @date 2016-8-11 下午2:00:54
 * @desp http://www.cnblogs.com/saga5998/
 * @email 573107773@qq.com
 */ 
@Controller
@RequestMapping("/applet/sapi")
public class SimpleLibAppletsController extends BaseControllerSupportImpl { 

	/***
	 * 日志
	 */
	private static final Logger logger = Logger.getLogger("LibAppletsController");   
	
	@Autowired 
    @Qualifier("simpleLibraryService")
	private LibraryService libraryService;
    
    @Autowired
    @Qualifier("sysReaderService")
    private SysReaderService readerService;
	
	/****
	 * 用户认证 
	 * @param code wx.login code
	 * @param type 登陆类型
	 * @return
	 * @date 2018年5月30日 上午9:59:03
	 */
	@RequestMapping(value={"/confirm/{code}/{type}"},method = RequestMethod.GET)
	@ResponseBody
	public DataResult<LoginInfo> confirm(@PathVariable("code") String code,@PathVariable("type") String type){
		if(logger.isDebugEnabled())
			logger.debug("alogin=====================code: "+code+" type: "+type); 
		DataResult<LoginInfo> result = new DataResult<LoginInfo>();
		LoginInfo li = new LoginInfo(); 
		String url = String.format(WechatConst.ALOGIN,DevApp.APPID,DevApp.AppSecret, code);
		try{
			if(logger.isDebugEnabled())
				logger.debug("begin=====================url: "+url); 
			String strJson = HttpUtil.getJson(url); 
			JSONObject o=JSONObject.fromObject(strJson); 
			li.setCode(code);
			li.setOpenid(o.get("openid") == null ? "" : o.get("openid").toString());
			li.setSession_key(o.get("session_key") == null ? "" : o.get("session_key").toString());
			if(logger.isDebugEnabled())
				logger.debug("end=====================li: "+JSONObject.fromObject(li).toString()); 
			result.addOK("检测成功", li);
		}catch(Exception ex)
		{
			logger.error(ex.getMessage());
			result.addError("用户检测失败");
		} 
		return result;
	}
	
    /****
     * 用户登陆
     * @param name 用户名
     * @param password 密码
     * @param openid openid
     * @param model 参数
     * @return
     * @date 2018年7月3日 下午12:31:26
     */
	@RequestMapping(value={"/login"},method = RequestMethod.POST)
	@ResponseBody
	public DataResult<String> login(@RequestParam("username") String name,
			@RequestParam(value="password",required=false) String password,
			@RequestParam("openid") String openid,Model model){
		if(logger.isDebugEnabled())
			logger.debug("login=====================username: "+name+" password: "+password); 
		DataResult<String> result = new DataResult<String>(); 
		try{ 
			
			SysReader query = new SysReader(); 
			query.setCampusCardNum(name);
			if(!StringEx.isExEmpty(password))
				query.setPassword(password);
			SysReader qr = readerService.queryOne(query);
			if(qr != null)
			{
				//更新wechat
				if(StringEx.isExEmpty(qr.getWechat()) && !StringEx.isExEmpty(openid))  
					qr.setWechat(openid);
				readerService.updateById(qr); 
				//登陆成功 
				result.addOK("登陆成功", name);		
			}else
			{
				result.addError("用户不存在或密码错误");
			} 
		}catch(Exception ex)
		{
			logger.error(ex.getMessage());
			result.addError("用户检测失败");
		} 
		return result;
	}
	
    @RequestMapping(value = {"/book/{id}"}, method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public DataResult<SysBookVo> getBook(@PathVariable("id") String id) {
        if (logger.isDebugEnabled()) {
        	logger.debug("getBook id: " + id);
        }
  
        DataResult<SysBookVo> result = new DataResult<SysBookVo>();  
        if(!StringEx.isExEmpty(id))
        {
        	SysBookVo sBook = null;//businessService.getBookInfo(id); 
            if (null != sBook) { 
                result.addOK("", sBook); 
            } else { 
                result.addError(String.format("没有%s图书信息", id));
            } 
        }else
        {
        	result.addError(String.format("查询%s图书参数不正确", id));
        } 
        return result;
    }
	
	
	public static void main(String[] args)
	{  
		String strJson = "{\"session_key\":\"suOP+5XMa2GTe9oGJnWN+Q==\",\"openid\":\"o9w6K5ZqxtxxKs77n82NTIpkjpf4\"}";
		JSONObject o=JSONObject.fromObject(strJson); 
		System.out.println("openid : "+(o.get("openid") == null ? "" : o.get("openid").toString()));
	}
	
}
